package com.jzbwlkj.windowmanager;

import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.jzbwlkj.windowmanager.service.WindowService;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 悬浮窗口
 */
public class MainActivity extends AppCompatActivity implements ServiceConnection
{
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    ClipboardManager cm;

    public static Context context;

    private Intent intent;
    private BroadcastReceiver msgReceiver;

    Spinner spinner;
    EditText txt;
    TextView showtxt;


    @Override
    protected void onNewIntent(Intent intent) {
        String action = intent.getAction();
        if(intent.ACTION_VIEW.equals(action))
        {

            Toast.makeText(getApplicationContext(),"new:"+intent.getDataString(),Toast.LENGTH_LONG).show();
//            Log.v(intent.getDataString());

        }


        super.onNewIntent(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {


        Intent intent = getIntent();

        String action = intent.getAction();
        if(intent.ACTION_VIEW.equals(action))
        {

            Toast.makeText(getApplicationContext(),"start:"+intent.getDataString(),Toast.LENGTH_LONG).show();
//            Log.v(intent.getDataString());

        }


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //动态注册广播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.communication.RECEIVER");
        registerReceiver(msgReceiver, intentFilter);

        showtxt = (TextView) findViewById(R.id.showtxt);
        txt = (EditText) findViewById(R.id.textView);
        spinner = (Spinner) findViewById(R.id.spinner);
        intent = new Intent(this, WindowService.class);
        context = MainActivity.this;
        cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        bindService(intent, this, BIND_AUTO_CREATE);

        //intent.setType(“image/*”);
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片


        String level[] = new String[]{"video/*", "audio/*", "image/*", "video/*;image/*",
                "setData"};

        ArrayAdapter<String> adapter = new MyArrayAdapter(getApplicationContext(), level);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        if (!TextUtils.isEmpty(读文本()))
        {
            txt.setText(读文本());
        }
        spinner.setSelection(读索引());

        cachedThreadPool.execute(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    try
                    {
                        Message msg = new Message();
                        handler.sendMessage(msg);
                        Thread.sleep(2000);
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            try
            {
                showtxt.setText(cm.getText().toString());
            } catch (Exception ex)
            {
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 点击事件
     *
     * @param view
     */
    public void click(View view)
    {
        try{
            switch (view.getId())
            {
                case R.id.bt_main_start://开启
                    startService(intent);
                    bindService(intent, this, BIND_AUTO_CREATE);
                    break;
                case R.id.bt_main_end://关闭
                    stopService(intent);
                    unbindService(this);
                    break;

            }
        }catch (Exception ex){}

    }

    @Override
    protected void onDestroy()
    {
//        stopService(intent);
//        unregisterReceiver(msgReceiver);
//        unbindService(this);
        super.onDestroy();
    }


    public void OpenUrl(View view)
    {
//        if (!TextUtils.isEmpty(txt.getText().toString()))
//        {
//            Intent intent = new Intent(Intent.ACTION_VIEW);    //为Intent设置Action属性
//            intent.setData(Uri.parse("http://www.baidu.com")); //为Intent设置DATA属性
//            startActivity(intent);


    }

    public void 播放MP4()
    {
        try
        {
            String playUrl = "";
            try
            {
                playUrl = cm.getText().toString();
            } catch (Exception ex)
            {
                Toast.makeText(getApplicationContext(), "取出文本有问题", Toast.LENGTH_LONG).show();
            }


            if (TextUtils.isEmpty(playUrl))
            {
                Toast.makeText(getApplicationContext(), "文本为空", Toast.LENGTH_LONG).show();
                return;
            }

//


//            playUrl=playUrl.replace("https://","http://");
//            playUrl =playUrl.substring(0,8)+java.net.URLEncoder.encode(playUrl.substring(8),
// "utf-8");

//            String allowedChars="._-$,:;~()/";
//             playUrl = Uri.encode(playUrl, allowedChars);
            playUrl = playUrl.replace("https://", "http://");
//           Toast.makeText(getApplicationContext(), playUrl, Toast.LENGTH_LONG).show();


            Uri uri = Uri.parse(playUrl);
            //调用系统自带的播放器
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            String str = "";
            if (!TextUtils.isEmpty(txt.getText().toString()))
            {
                str = txt.getText().toString();
            } else
            {
                str = spinner.getSelectedItem().toString();
            }
            if (str.equals("setData"))
            {
                intent.setData(uri);
            } else
            {

                intent.setDataAndType(uri, str);
            }

            startActivity(intent);
        } catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
        }

    }


    WindowService msgService;
    private PackageManager mPackageManager;
    private List<ResolveInfo> mAllApps;

    private void openApp(String str)
    {
        //应用过滤条件
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        System.out.println("testrrr");
        mPackageManager = this.getPackageManager();
        System.out.println("tesr");
        mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
        //按报名排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));

        for (ResolveInfo res : mAllApps)
        {
            //该应用的包名和主Activity
            String pkg = res.activityInfo.packageName;
            String cls = res.activityInfo.name;
            System.out.println("pkg---" + pkg);
            // System.out.println("打印出来的----" + str);

            // 打开QQ pkg中包含"qq"，打开微信，pkg中包含"mm"
            if (pkg.contains(str))
            {
                ComponentName componet = new ComponentName(pkg, cls);
                Intent intent = new Intent();
                intent.setComponent(componet);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                this.startActivity(intent);
            }
        }
    }

    public void onOpen(View view)
    {
        播放MP4();
        //openApp("isafe");
    }

    public void onC(View view)
    {
        if (msgService.是否贴屏)
        {
            ((Button) view).setText("不贴屏");
            msgService.是否贴屏 = false;
        } else
        {
            ((Button) view).setText("贴屏");
            msgService.是否贴屏 = true;
        }

    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder)
    {
        msgService = ((WindowService.MsgBinder) iBinder).getService();
//

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName)
    {

    }


    /**
     * 广播接收器
     *
     * @author len
     */
    public class MsgReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            //拿到进度，更新UI
//            int progress = intent.getIntExtra("progress", 0);
//            mProgressBar.setProgress(progress);

            播放MP4();


            保存文本(txt.getText().toString());
        }


    }

    private void 保存文本(String msg)
    {
        try
        {
            SharedPreferences settings = getSharedPreferences("db", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("txt", msg);
            editor.putInt("index", spinner.getSelectedItemPosition());
            // 提交本次编辑
            editor.commit();
        } catch (Exception ex)
        {

        }
    }

    private String 读文本()
    {
        SharedPreferences settings = getSharedPreferences("db", 0);

        return settings.getString("txt", "");
    }

    private int 读索引()
    {
        SharedPreferences settings = getSharedPreferences("db", 0);

        return settings.getInt("index", 0);
    }
//    }
}
